package tool;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import constant.ConfigConstants;
import entity.Top;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import util.ParamUtil;
import java.awt.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Intellij IDEA.
 * User:  老赵
 * Date:  2023/7/19
 */
public class TopHot {

    public static void openTopStage() {
        Stage stature = new Stage();
        stature.setTitle("热搜");
        stature.setFullScreen(ConfigConstants.FullScreen);

        GridPane gridPane = new GridPane();
        gridPane.setPadding(new Insets(10)); // 设置内边距为10像素
        gridPane.setVgap(10); // 设置垂直间距为10像素
        gridPane.setHgap(10); // 设置水平间距为10像素

        Button searchButton = new Button("热度查询");
        gridPane.addRow(0, searchButton);

        TableView<Top> tableView = new TableView<>();
        tableView.setMinWidth(400);
        tableView.setMinHeight(500);
        tableView.setRowFactory(tv -> new TableRow<Top>() {
            @Override
            protected void updateItem(Top item, boolean empty) {
                super.updateItem(item, empty);
                if (item == null || empty) {
                    setStyle(""); // 如果行为空，则不设置样式
                } else {
                    int rowIndex = getIndex(); // 获取当前行的索引
                    if (rowIndex == 0) {
                        setStyle("-fx-background-color: #e8409a;"); // 设置热度最高的行的背景颜色为红色
                    } else {
                        double opacity = 1 - (rowIndex * 0.1); // 根据行索引设置不同的透明度
                        setStyle("-fx-background-color: rgba(231, 156, 196, " + opacity + ");"); // 设置其他行的背景颜色和透明度
                    }
                }
            }
        });
        // 创建"热度"列
        TableColumn<Top, String> popularityColumn = new TableColumn<>("热度");
        popularityColumn.setCellValueFactory(new PropertyValueFactory<>("hotWordNum"));
        popularityColumn.setMinWidth(50);
        // 创建"详情"列
        TableColumn<Top, String> detailsColumn = new TableColumn<>("详情");
        detailsColumn.setCellValueFactory(new PropertyValueFactory<>("hotWord"));
        detailsColumn.setMinWidth(300);
        detailsColumn.setCellFactory(column -> {
            return new TableCell<Top, String>() {
                @Override
                protected void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty);
                    if (item == null || empty) {
                        setText(null);
                    } else {
                        setText(item);
                        setWrapText(true); // 设置自动换行
                    }
                }
            };
        });
        // 创建"查看"列
        TableColumn<Top, String> watchColumn = new TableColumn<>("查看");
        watchColumn.setCellValueFactory(new PropertyValueFactory<>("url"));
        watchColumn.setMinWidth(50);
        watchColumn.setCellFactory(column -> {
            return new TableCell<Top, String>() {
                @Override
                protected void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty);
                    if (item == null || empty) {
                        setText(null);
                        setGraphic(null);
                    } else {
                        Hyperlink hyperlink = new Hyperlink("查看");
                        hyperlink.setOnAction(e -> {
                            if (Desktop.isDesktopSupported()) {
                                try {
                                    Desktop.getDesktop().browse(new URI(item));
                                } catch (IOException | URISyntaxException ex) {
                                    Alert alert = new Alert(Alert.AlertType.ERROR);
                                    alert.setTitle("警告");
                                    alert.setHeaderText(null);
                                    alert.setContentText(ex.getMessage());
                                    alert.showAndWait();
                                    ex.printStackTrace();
                                }
                            }
                        });
                        setGraphic(hyperlink);
                    }
                }
            };
        });

        tableView.getColumns().addAll(popularityColumn, detailsColumn, watchColumn);
        // 设置表格边框隐藏
        tableView.setStyle("-fx-padding: 0; -fx-background-color: transparent; -fx-table-cell-border-color: transparent;");
        // 将 TableView 放置在 GridPane 的第一行，占据一整行
        GridPane.setConstraints(tableView, 0, 1, 1, GridPane.REMAINING);
        gridPane.getChildren().add(tableView);

        searchButton.setOnAction(event -> {
            ObservableList<Top> topList = getTop(ParamUtil.getTopToken());
            if (CollectionUtil.isNotEmpty(topList)) {
                tableView.setItems(topList);
            }
        });

        Scene scene = new Scene(gridPane, 500, 700);
        stature.setScene(scene);
        stature.show();
    }

    private static ObservableList<Top> getTop(String topToken) {
        ObservableList<Top> dataList = FXCollections.observableArrayList();
        String url = "https://v2.alapi.cn/api/new/wbtop?num=20"+ "&token=" + topToken;
        String html = HttpUtil.get(url);
        JSONObject jsonObject = JSONUtil.parseObj(html);
        if (HttpStatus.HTTP_OK == jsonObject.getInt("code")) {
            List<Top> topList = new ArrayList<>();
            JSONArray array = (JSONArray) jsonObject.get("data");
            for (int i = 0; i < array.size(); i++) {
                JSONObject object = (JSONObject) array.get(i);
                dataList.add(new Top(object.getStr("hot_word_num"),object.getStr("hot_word"),object.getStr("url")));
            }
            return dataList;
        } else {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("警告");
            alert.setHeaderText(null);
            alert.setContentText(jsonObject.getStr("msg"));
            alert.showAndWait();
            return null;
        }
    }
}
